<template>
  <div class="search-container">
    <div class="search-header">
      <h2>商品搜索</h2>
    </div>
    
    <div class="search-form">
      <div class="search-row">
        <div class="search-input-group">
          <input
            v-model="searchForm.keyword"
            type="text"
            placeholder="搜索商品名称或描述..."
            class="search-input"
            @keyup.enter="performSearch"
          />
          <button @click="performSearch" class="search-btn">
            <span>🔍</span>
          </button>
        </div>
      </div>
      
      <div class="filter-row">
        <div class="filter-group">
          <label>分类：</label>
          <select v-model="searchForm.categoryId" class="filter-select">
            <option value="">全部分类</option>
            <option v-for="(name, id) in categoryMap" :key="id" :value="id">
              {{ name }}
            </option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>价格范围：</label>
          <input
            v-model.number="searchForm.minPrice"
            type="number"
            placeholder="最低价"
            class="price-input"
          />
          <span class="price-separator">-</span>
          <input
            v-model.number="searchForm.maxPrice"
            type="number"
            placeholder="最高价"
            class="price-input"
          />
        </div>
        
        <div class="filter-group">
          <label>
            <input
              v-model="searchForm.isHot"
              type="checkbox"
              :true-value="1"
              :false-value="null"
            />
            仅显示热销商品
          </label>
        </div>
        
        <button @click="clearFilters" class="clear-btn">清除筛选</button>
      </div>
    </div>
    
    <div class="search-results">
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        搜索中...
      </div>
      
      <div v-else-if="error" class="error-message">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ error }}</div>
        <button class="retry-btn" @click="performSearch">重试</button>
      </div>
      
      <div v-else-if="products.length === 0" class="empty-message">
        <div class="empty-icon">🔍</div>
        <div class="empty-text">未找到相关商品</div>
        <div class="empty-suggestion">请尝试调整搜索条件</div>
      </div>
      
      <div v-else class="results-info">
        <div class="results-count">找到 {{ products.length }} 个商品</div>
      </div>
      
      <div v-if="products.length > 0" class="product-grid">
        <div
          v-for="product in products"
          :key="product.productId"
          class="product-card"
          @click="goToProductDetail(product.productId)"
        >
          <div class="product-image">
            <img :src="getProductImage(product)" :alt="product.productName" />
            <span v-if="product.isHot === 1" class="hot-tag">热销</span>
          </div>
          
          <div class="product-info">
            <h3 class="product-name">{{ product.productName }}</h3>
            <div class="price-section">
              <span class="current-price">¥{{ formatPrice(product.sellingPrice) }}</span>
              <span v-if="product.originalPrice" class="original-price">¥{{ formatPrice(product.originalPrice) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '../../utils/request';

// 响应式数据
const products = ref([]);
const loading = ref(false);
const error = ref(null);

const categoryMap = ref({
  1: '建筑起重机械',
  2: '工程起重器械',
  3: '路面机械',
  4: '土方机械',
  5: '环卫机械',
  6: '工业车辆',
  7: '模型专区',
  8: '特惠专区',
  9: '运费'
});

const searchForm = reactive({
  keyword: '',
  categoryId: '',
  minPrice: null,
  maxPrice: null,
  isHot: null
});

// 获取router和route
const router = useRouter();
const route = useRoute();

// 方法
const formatPrice = (price) => {
  const num = Number(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

const goToProductDetail = (productId) => {
  const id = Number(productId);
  if (isNaN(id)) {
    console.error('Invalid product ID:', productId);
    return;
  }
  router.push(`/product/${id}`).catch(err => {
    console.error('Navigation failed:', err);
  });
};

const getProductImage = (product) => {
  return product.productImg || require('@/assets/product-default.png');
};

const performSearch = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const params = new URLSearchParams();
    
    if (searchForm.keyword) {
      params.append('keyword', searchForm.keyword);
    }
    if (searchForm.categoryId) {
      params.append('categoryId', searchForm.categoryId);
    }
    if (searchForm.minPrice) {
      params.append('minPrice', searchForm.minPrice);
    }
    if (searchForm.maxPrice) {
      params.append('maxPrice', searchForm.maxPrice);
    }
    if (searchForm.isHot) {
      params.append('isHot', searchForm.isHot);
    }
    
    const response = await request.get(`/products/search/advanced?${params.toString()}`);
    products.value = response.data;
    
  } catch (err) {
    console.error('搜索失败:', err);
    error.value = err.response?.data?.message || '搜索失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const clearFilters = () => {
  searchForm.keyword = '';
  searchForm.categoryId = '';
  searchForm.minPrice = null;
  searchForm.maxPrice = null;
  searchForm.isHot = null;
  products.value = [];
  error.value = null;
};

// 监听URL参数变化
watch(() => route.query.q, (newQuery) => {
  if (newQuery) {
    searchForm.keyword = newQuery;
    performSearch();
  }
}, { immediate: true });

// 组件挂载时检查URL参数
onMounted(() => {
  if (route.query.q) {
    searchForm.keyword = route.query.q;
    performSearch();
  }
});
</script>

<style scoped>
.search-container {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-header {
  margin-bottom: 20px;
}

.search-header h2 {
  font-size: 1.5rem;
  color: #333;
  margin: 0;
}

.search-form {
  margin-bottom: 30px;
}

.search-row {
  margin-bottom: 20px;
}

.search-input-group {
  display: flex;
  max-width: 500px;
}

.search-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px 0 0 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #f5222d;
}

.search-btn {
  padding: 12px 20px;
  background: #7dabe1;
  color: white;
  border: none;
  border-radius: 0 8px 8px 0;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background: #0004e0;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  min-width: 120px;
}

.price-input {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

.price-separator {
  color: #666;
  font-weight: 500;
}

.clear-btn {
  padding: 8px 16px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.clear-btn:hover {
  background: #5a6268;
}

.loading {
  padding: 2rem;
  text-align: center;
  color: #666;
  font-size: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #7dabe1;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  padding: 2rem;
  text-align: center;
  background-color: #fff1f0;
  border-radius: 8px;
  margin: 1rem 0;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.error-text {
  color: #f5222d;
  margin-bottom: 1rem;
}

.retry-btn {
  padding: 0.5rem 1.5rem;
  background-color: #7dabe1;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.empty-message {
  padding: 3rem;
  text-align: center;
  color: #666;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-text {
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
}

.empty-suggestion {
  color: #999;
}

.results-info {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.results-count {
  color: #666;
  font-size: 0.9rem;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.hot-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #f5222d;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.product-info {
  padding: 15px;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px;
  height: 44px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-section {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.current-price {
  font-size: 18px;
  color: #f5222d;
  font-weight: bold;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group {
    justify-content: space-between;
  }
  
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .product-grid {
    grid-template-columns: 1fr;
  }
  
  .search-input-group {
    flex-direction: column;
  }
  
  .search-input {
    border-radius: 8px 8px 0 0;
  }
  
  .search-btn {
    border-radius: 0 0 8px 8px;
  }
}
</style> 